/*******************************************************************************
 * The MOSES project, model based software engineering of networked embedded systems.
 * 
 * Copyright (C) 2010-2013, University of Applied Sciences Wildau,
 * Telematics Research Group, http://www.tm.th-wildau.de/research-group
 * 
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, see <http://www.gnu.org/licenses>.
 * 
 * Contributors:
 *     University of Applied Sciences Wildau - initial API and implementation
 * 
 * If you are interested in a commercial license please contact us via 
 * e-mail: ralf.vandenhouten@th-wildau.de.
 ******************************************************************************/
package de.thwildau.tm.moses.avro.ui.builder;

import java.io.Closeable;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;

import org.apache.avro.AvroRuntimeException;
import org.apache.avro.Protocol;
import org.apache.avro.compiler.idl.Idl;
import org.apache.avro.compiler.idl.ParseException;
import org.apache.avro.compiler.specific.SpecificCompiler;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.jface.preference.IPreferenceStore;

import de.thwildau.tm.moses.avro.ui.Activator;
import de.thwildau.tm.moses.avro.ui.preferences.PreferenceConstants;

/**
 * This class is a compiler task that generates a JSON schema from an Avro IDL file.
 * 
 * @author Thomas Kistel
 * @version $Revision: 766 $
 */
public class AvroIdlCompilerTask implements AvroCompilerTask {
    
    private static final String LOG_PREFIX = "IdlCompiler: ";

    /*
     * (non-Javadoc)
     * @see de.thwildau.tm.moses.avro.ui.builder.AvroCompilerTask#doCompile(java.io.File, java.io.File)
     */
    @Override
    public void doCompile(File srcIdl, File destDir) throws CoreException {
        IPreferenceStore prefStore = Activator.getInstance().getPreferenceStore();
        boolean compileToJava = prefStore.getBoolean(PreferenceConstants.PREF_KEY_COMPILE_JAVA);
        if(!compileToJava)
            return;
        
        Idl parser = null;
        PrintStream parseOut = null;
        try {
            parser = new Idl(srcIdl);
            File destFile = new File(destDir, getSchemaFilename(srcIdl));
            parseOut = new PrintStream(new FileOutputStream(destFile));

            Activator.debugInfo(LOG_PREFIX + "Compiling IDL file " + srcIdl.getName() + " to " + destFile.getName());

            Protocol p = parser.CompilationUnit();
            parseOut.print(p.toString(true));

            // compile the generated schema file to Java
            compileSchemaToJava(destFile);

        } catch (ParseException e) {
            throw new CoreException(Activator.toStatus(IStatus.WARNING, LOG_PREFIX + "Could not compile avro idl file to schema.", e));
        } catch (IOException e) {
            throw new CoreException(Activator.toStatus(IStatus.ERROR, LOG_PREFIX + "Could not parse avro idl file.", e));
        } catch (Exception e) {
            throw new CoreException(Activator.toStatus(IStatus.ERROR, LOG_PREFIX + "Unexpected error when processing schema file " + srcIdl.getName(), e));
        } finally {
            closeSave(parser);
            closeSave(parseOut);
        }
    }

    private void compileSchemaToJava(File schemaFile) throws CoreException, IOException {
        try {
            File dir = schemaFile.getParentFile();
            String message = LOG_PREFIX + "Compiling schema file " + schemaFile.getName() + " to dir " + dir.getName();
            Activator.debugInfo(message);
            SpecificCompiler.compileProtocol(schemaFile, dir);
        } catch (AvroRuntimeException e) {
            throw new CoreException(Activator.toStatus(IStatus.WARNING, LOG_PREFIX + "Could not parse schema file " + schemaFile.getName(), e));
        }
    }
    
    /**
     * Returns the name of the Schema file. The file name will be the same as the IDL
     * file, with the 'avpr' file extension.
     * 
     * @param idlFile the IDL file
     * @return the name of the Schema file
     */
    protected String getSchemaFilename(File idlFile) {
        String name = idlFile.getName();
        return name.substring(0, name.indexOf(".")) + ".avpr";
    }
    
    public static void closeSave(Closeable closeable) {
        try {
            if(closeable != null)
                closeable.close();
        } catch (IOException e) {
            // ignore
        }
    }
}
